package com.azure.bigstore.controller;

import com.azure.bigstore.entity.*;
import com.azure.bigstore.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.Date;
import java.util.List;

/**
 * Created by liuhuaibin on 2018/1/22.
 */
@RestController
@RequestMapping("/v1")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @GetMapping("/products")
    public List<Product> getProducts(){
        return productService.getProducts();
    }
    @GetMapping("/productsOrderByCategory")
    public List<Product> getProductsOrderByCategory(){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String t = request.getHeader("t");
        System.out.println("tttt:"+t);
        if(t != null && t != ""){
            Token token = tokenService.findByToken(t);
            //未查询到token
            if(token == null){
                response.setStatus(444);
            }else{
                if(token.getValidityTime().after(new Date())){
                    long time = new Date().getTime()+1800000;//延长30分钟
                    System.out.println("new:"+new Date()+"  time"+new Date(time));
                    token.setValidityTime(new Date(time));
                    tokenService.saveToken(token);
                }else{
                    response.setStatus(444);
                }
            }
        }
        return productService.getProductsOrderByCategory();
    }
    @GetMapping("/products/{id}")
    public Product getProducts(@PathVariable String id){
        return productService.getProduct(id);
    }
    @PostMapping("/products")
    public Product addProduct(Long ID,String title,String msg,String cover,String category,int price,  MultipartFile file){
        //System.out.println("---addProduct controller product:"+product+"  file:"+file);
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Product product = null;
        if(ID != null)
            product = new Product(ID,title,msg,category,cover,price);
        else
            product = new Product(title,msg,category,cover,price);
        return productService.saveProduct(product,file,req);
    }
    @PostMapping("/orderProducts")
    public String orderProducts(){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String t = request.getHeader("t");
        String p = request.getHeader("p");
        String n = request.getHeader("n");
        System.out.println("t:"+t+" p:"+p+" n:"+n);
        if((("".equals(p) || "".equals(n))) ){
            response.setStatus(444);
        }else if(t != null && t != ""){
            Token token = tokenService.findByToken(t);
            //未查询到token
            if(token == null){
                response.setStatus(444);
            }else{
                if(token.getValidityTime().after(new Date())){
                    long time = new Date().getTime()+1800000;//延长30分钟
                    System.out.println("new:"+new Date()+"  time"+new Date(time));
                    token.setValidityTime(new Date(time));
                    tokenService.saveToken(token);
                    //search userinfo
                    User u = userService.findUserInfo(token.getUid());
                    System.out.println("orderProducts>>user:"+u);
                    User userInfo = new User("","",u.getAddr_sheng(),u.getAddr_shi(),u.getAddr_qu_xian(),
                                                u.getAddr_xiang_jiedao(),u.getAddr_other(),u.getName(),u.getPhone(),new Date());
                    String addr = userInfo.getAddr_sheng()+userInfo.getAddr_shi()+userInfo.getAddr_qu_xian()
                                        +userInfo.getAddr_xiang_jiedao()+" "+userInfo.getAddr_other();
                    //create order
                    Order order = new Order(addr,userInfo.getName(),userInfo.getPhone(),token.getUid(),0,new Date());
                    Order reOrder = orderService.addOrder(order);
                    String[] pids = p.split(",");
                    String[] nums = n.split(",");
                    //create orderitem
                    int totalprice = 0;
                    for(int i = 0; i < pids.length; i ++){
                        OrderItem orderItem = new OrderItem(reOrder.getID(),Long.valueOf(pids[i]),Integer.valueOf(nums[i]),new Date());
                        orderItemService.saveOrderItem(orderItem);
                        totalprice += (productService.getProduct(String.valueOf(pids[i])).getPrice() ) * (Integer.valueOf(nums[i]));
                    }
                    reOrder.setTotal(totalprice);
                    orderService.addOrder(reOrder);
                    System.out.println("=====reOrder:"+reOrder.toString());
                    return "success";
                }else{
                    response.setStatus(444);
                }
                return "bad";
            }
        }else{
            response.setStatus(444);
        }
        return "bad";
    }
    @DeleteMapping("/products/{id}")
    public void deleteProduct(@PathVariable String id){
        productService.deleteProduct(id);
    }

}
